<template>
<view class="page-wrap">
  <!--  {{ formData }}-->
  <u-picker mode="time" v-model="datePickerOption.show" :default-time="datePickerOption.defaultTime"
            :params="{year: true,month: true,day: true}"
            @confirm="onSelectDate"
  ></u-picker>
  <u-picker mode="selector" v-model="selectOption.show" :default-selector="[selectOption.defaultIndex]"
            :range="selectOption.list" @confirm="onSelect"></u-picker>

  <!--  证书-->
  <view class="form-wrap" v-if="formType === 'ce'">
    <view class="form-item">
      <view class="label">
        <text>证书类型</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <u-radio-group v-model="formData.type">
          <u-radio name="1">中国职业经理人协会</u-radio>
          <u-radio name="2">商业国际交流中心</u-radio>
        </u-radio-group>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>姓名</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.name" placeholder="请输入姓名" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>证件号</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.id_card" placeholder="请输入证件号" placeholder-class="input-placeholder"/>
      </view>
    </view>
  </view>

  <!--  产品-->
  <view class="form-wrap" v-if="formType === 'mp'">
    <view class="form-item">
      <view class="label">
        <text>产品名称</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.name" placeholder="请输入产品名称" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>最高额度（万）</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.limit" placeholder="请输入最高额度（万）" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>年化利率（%）</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.rate"
               placeholder="请输入年化利率（%）" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>产品优势</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <textarea v-model="formData.advantage"
                  rows="3"
                  style="height: 200rpx;"
                  placeholder="请输入产品优势" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>底部显示</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <u-radio-group v-model="formData.is_show">
          <u-radio name="1">不显示</u-radio>
          <u-radio name="2">显示</u-radio>
        </u-radio-group>
      </view>
    </view>
  </view>

  <view class="form-wrap" v-if="formType === 'ed'">
    <view class="form-item">
      <view class="label">
        <text>学校</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.name"
               placeholder="请输入学校名称" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>学历</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <view class="select-view" :class="formData.educational_background && 'active'"
              @click="onSelectPickerOpen('educational_background')">
          {{ formData.educational_background || '请选择学历' }}
        </view>

      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>教育时间</text>
        <text class="require">*</text>
      </view>
      <view class="value range-time">
        <view class="st" :class=" formData.start_date && 'active'" @click="onOpenDatePicker('s','start_date')">
          {{ formData.start_date || '开始时间' }}
        </view>
        <view class="ss">-</view>
        <view class="et" :class=" formData.end_date && 'active'" @click="onOpenDatePicker('e','end_date','start_date')">
          {{ formData.end_date || '至今' }}
        </view>
      </view>
    </view>
  </view>

  <view class="form-wrap" v-if="formType === 'wk'">
    <view class="form-item">
      <view class="label">
        <text>公司名称</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.name"
               placeholder="请输入公司名称" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>职位名称</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.position"
               placeholder="请输入公司名称" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>工作时间</text>
        <text class="require">*</text>
      </view>
      <view class="value range-time">
        <view class="st" :class=" formData.start_date && 'active'" @click="onOpenDatePicker('s','start_date')">
          {{ formData.start_date || '开始时间' }}
        </view>
        <view class="ss">-</view>
        <view class="et" :class=" formData.end_date && 'active'" @click="onOpenDatePicker('e','end_date','start_date')">
          {{ formData.end_date || '至今' }}
        </view>
      </view>
    </view>
  </view>

  <view class="form-wrap" v-if="formType === 'ue'">
    <view class="form-item">
      <view class="label">
        <text>案例标题</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <input v-model="formData.title"
               placeholder="请输入案例标题" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>客户情况</text>
        <text class="require">*</text>
      </view>
      <view class="value">
          <textarea v-model="formData.situation"
                    rows="3"
                    style="height: 100rpx;"
                    placeholder="客户情况" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>难点描述</text>
        <text class="require">*</text>
      </view>
      <view class="value">
          <textarea v-model="formData.describe"
                    rows="3"
                    style="height: 100rpx;"
                    placeholder="客户情况" placeholder-class="input-placeholder"/>
      </view>
    </view>
    <view class="form-item">
      <view class="label">
        <text>图片</text>
        <text class="require">*</text>
      </view>
      <view class="value">
        <view class="w-full">
          <uploader @after-read="afterRead"
                    :file-list="formData.abs_image"
                    :max-upload="6"
                    :deletable="true"
                    :mutiple="true"
                    @delete="handleDelete">


          </uploader>

        </view>
      </view>

    </view>
  </view>

  <view class="footer-wrap">
    <u-button :loading="saveLoading" :hair-line="false" type="primary"
              :custom-style="{background: '#187DFF',borderColor:'unset'}"
              @click="onSave">
      保存
    </u-button>
  </view>
</view>
</template>

<script>

import {
  apiArticleGoodsAdd, apiArticleGoodsEdit, apiCaseAdd, apiCaseEdit,
  apiCertificateAdd,
  apiEducationAdd,
  apiEducationEdit,
  apiWorkAdd,
  apiWorkEdit
} from "../../api/super_card.js";
import {uploadFile} from "../../../utils/tools.js";

const toast = (msg) => {
  uni.showToast({
    icon: 'none',
    title: msg
  });
}

const apiMap = {
  'ce': {
    api: apiCertificateAdd,
    check: (formData) => {
      const d = {...formData};
      if (!d.type) {
        throw new Error('请选择证书类型');
      }
      if (!d.name) {
        throw new Error('请输入姓名');
      }
      if (!d.id_card) {
        throw new Error('请输入证件号');
      }
      return d;
    },
    formData: {
      type: '',
      name: '',
      id_card: ''
    }
  },
  'mp': {
    api: apiArticleGoodsAdd,
    editApi: apiArticleGoodsEdit,
    check: (formData) => {
      const d = {...formData};
      if (!d.name) {
        throw new Error('请输入产品名称');
      }
      if (!d.limit) {
        throw new Error('请输入最高额度');
      }
      if (!d.rate) {
        throw new Error('请输入年化利率');
      }
      if (!d.advantage) {
        throw new Error('请输入产品优势');
      }
      if (!d.is_show) {
        throw new Error('请选择底部是否显示');
      }
      return d;
    },
    formData: {
      name: '',
      limit: '',
      rate: '',
      advantage: '',
      is_show: 0,
    }
  },
  'ed': {
    api: apiEducationAdd,
    editApi: apiEducationEdit,
    check: (formData) => {
      const d = {...formData};
      if (!d.end_date) {
        d.end_date = '至今';
      }
      if (!d.name) {
        throw new Error('请输入学校');
      }
      if (!d.educational_background) {
        throw new Error('请选择学历');
      }
      if (!d.start_date) {
        throw new Error('请选择开始时间');
      }
      return d;
    },
    formData: {
      name: '',
      educational_background: '',
      start_date: '',
      end_date: '',
    }
  },
  'wk': {
    api: apiWorkAdd,
    editApi: apiWorkEdit,
    check: (formData) => {
      const d = {...formData};
      if (!d.end_date) {
        d.end_date = '至今';
      }

      if (!d.name) {
        throw new Error('请输入公司名');
      }

      if (!d.position) {
        throw new Error('请输入公司职位');
      }

      if (!d.start_date) {
        throw new Error('请选择开始时间');
      }
      return d;
    },
    formData: {
      name: '',
      position: '',
      start_date: '',
      end_date: '',
    }
  },
  'ue': {
    api: apiCaseAdd,
    editApi: apiCaseEdit,
    check: (formData) => {
      const d = {...formData};
      d.image = d.abs_image.map(item => item.url).join(',');
      if (!d.title) {
        throw new Error('请输入案例标题');
      }
      if (!d.situation) {
        throw new Error('请输入客户情况');
      }

      if (!d.describe) {
        throw new Error('请输入难点描述');
      }

      if (!d.image) {
        throw new Error('请上传案例图片');
      }

      return d;
    },
    formData: {
      title: '',
      situation: '',
      describe: '',
      image: '',
      abs_image: []
    }
  }
};

export default {
  data() {
    return {
      selectOption: {
        list: [
          '小学',
          '初中',
          '高中',
          '大专',
          '本科',
          '硕士',
          '研究生',
        ],
        defaultIndex: 0,
        show: false,
        field: ''
      },
      datePickerOption: {
        show: false,
        defaultTime: '',
        field: '',
        targetDefaultText: '至今'
      },
      formType: '',
      formData: {},
      saveLoading: false,
      isEdit: false
    };
  },
  onLoad({formType, id}) {
    this.isEdit = id;
    this.formType = formType;
    this.formData = apiMap[formType].formData;
    if (this.isEdit) {
      let data = uni.getStorageSync(formType + '_data');
      this.formData = data;
    }

  },
  methods: {
    async onSave() {
      let d = this.formData;
      const {check, api, editApi} = await apiMap[this.formType];
      try {
        d = await check(d);
        this.saveLoading = true;
        const result = this.isEdit ? await editApi(d) : await api(d);
        if (result.code == 1) {
          uni.$u.toast('保存成功');
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.$u.toast(result.msg);
        }
      } catch (e) {
        uni.$u.toast(e.message);
      } finally {
        this.saveLoading = false;
      }
    },
    onOpenDatePicker(type, field, prevField = undefined) {
      if (type === 's') {
        this.datePickerOption.defaultTime = this.formData[field];
      }
      if (type === 'e') {
        if (!this.formData[prevField]) {
          uni.$u.toast('请选择开始时间');
          return;
        }
        this.datePickerOption.defaultTime = this.formData[field] ? this.formData[field] : this.formData[prevField];
      }

      this.datePickerOption.show = true;
      this.datePickerOption.field = field;

    },
    onSelectDate(ev) {
      let date = `${ev.year}-${ev.month}-${ev.day}`;
      this.formData[this.datePickerOption.field] = date;
    },
    onSelectPickerOpen(field) {
      let index = this.selectOption.list.findIndex(item => this.formData[field] === item);
      this.selectOption.field = field;
      this.selectOption.defaultIndex = index;
      this.selectOption.show = true;
    },
    onSelect(ev) {
      let [index] = ev;
      if (index == -1) index = 0;
      this.formData[this.selectOption.field] = this.selectOption.list[index];
    },
    afterRead(e) {
      const file = e;
      uni.showLoading({
        title: '正在上传中...',
        mask: true
      });
      file.forEach(item => {
        uploadFile(item.path).then(res => {
          uni.hideLoading();
          this.formData.abs_image.push(res);
        });
      })
    },
    handleDelete(index, a) {
      this.formData.abs_image.splice(index, 1);
    },
  }
}
</script>

<style scoped lang="scss">
.page-wrap {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.upload-add {
  background-color: #efefef;
  height: 200rpx;
  width: 200rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20rpx;
}

.select-view {
  color: #BABABA;
}

.select-view.active {
  color: #666666 !important;

}

.range-time {
  display: flex;

  .active {
    color: #666666 !important;
  }

  .st, .et {
    flex: 1;
    font-weight: 400;
    font-size: 28rpx;
    color: #BABABA;
  }

  .ss {
    margin-right: 30rpx;
    color: #666666;
  }
}

.footer-wrap {
  padding: 30rpx;
}

.form-wrap {
  background-color: white;
  padding: 30rpx;

  input, textarea {
    font-weight: 400;
    font-size: 28rpx;
    color: #666666;
  }

  .input-placeholder {
    color: #BABABA;
  }


  .form-item {
    padding-bottom: 10rpx;
    margin-bottom: 40rpx;
    border-bottom: 1px solid #EEEEEE;

    &:last-child {
      border-bottom: unset;
    }

    .label {
      font-weight: 500;
      letter-spacing: 3rpx;
      margin-bottom: 20rpx;

      .require {
        color: red;
        padding-left: 6rpx;
      }
    }
  }
}
</style>
